
impact =
{

  widgets:
  {

	impact_correlation: function()
    {
      var self = this;
      self.render = function()
      {
          $(self.element).empty()
 	  	  self.paper.clear();
          switch(self.props['display-style'])
          {
	          case 'total-pie':
	        	  self.render_total_pie()
	        	  break;
	       	  case 'total-bar':
	        	  self.render_total_bar()
	        	  break;
	          case 'trend':
	          	self.render_trend()
          		break;
          }
   	   $(self.element).append('<div class="widget-icons">&nbsp;</div>');
      }
       self.render_total_pie = function()
       {
    	   var pie_data = []
    	   $(self.element).append("<b>Pie Chart</b><br/>")
    	   for(var i = 0;i < self.data.corr.length;i++)
    	   {
    	     var c = self.data.corr[i];
    	     pie_data.push({name: c.name, value: c.values[0].data.value})
    	     $(self.element).append(c.name+" "+c.values[0].data.value+" ["+c.values.length+"]"+"<br/>")
	       }

		   impact.util.pie(self,pie_data)
       }
       self.render_total_bar = function()
       {
       	   $(self.element).append("<b>Bar Chart</b><br/>")
    	   for(var i = 0;i < self.data.corr.length;i++)
    	  {
    	   	var c = self.data.corr[i];
    		$(self.element).append(c.name+" "+c.values[0].data.value+" ["+c.values.length+"]"+"<br/>")
	      }
       }
       self.render_trend = function()
       {
   	   	   console.log(self.data)
		   $(self.element).append("<b>Graph</b><br/>");
   	   	

		    var dvals = self.data.corr[0].values
			var dvalmin = dvals[0].data.value;		
			var dvalmax = dvals[0].data.value;
			for(var k = 0;k < self.data.corr.length;k++)
			{
				var dvals = self.data.corr[k].values
				for(var i = 1;i < dvals.length;i++)
				{
					dvalmin = Math.min(dvalmin, dvals[i].data.value);
					dvalmax = Math.max(dvalmax, dvals[i].data.value);
				}
			}
		 
			
	     //var line_vals = [ [], [], [], [], [], [], [], [], [], [] ];			
	     for (var j = 0; j< self.data.corr.length; j++)
	     { 
	    	 impact.util.line(self,self.data.corr[j].values,dvalmin,dvalmax)
	     	
	    	 // var a = line_vals[j];
	     	 //for(var i = 0;i < self.data.corr[j].values.length;i++)
	     	//	 a[i] = self.data.corr[j].values[i].data.value;
	     }
	     return;
           
           var dvalmin = 0;
           var dvalrange = 100;
           var w = 20;
           var h = 100;
           var path = "";
          // console.log(line_vals);
           for (var a=0; a<line_vals.length; a++)
           {
        	   if (line_vals[a]!=null)
        		   for(var i = 0;i < line_vals[a].length;i++)
        	        {
        	            var val  = line_vals[a][i];

        	            var x = self.width-i*w-w*.5;
        	            var y = h-(((val-dvalmin)/dvalrange)*h)+25;
        	            if (i!=0) path += "L ";
        	            path += x+" "+y+" ";
        	            var c = self.paper.circle(x,y,5).attr({fill:'#444'})
        	            c.val = val;
        	            c.click(function(){alert(this.val)});
        	            c.mouseover(function (event) {
        	                this.attr({fill: "#0f0"});
        	            });
        	            c.mouseout(function (event) {
        	                this.attr({fill: "#444"});
        	            });
        	         }
           }
       }
    },
    
    facebook_get_friends: function()
    {
    	var self = this;
        self.title = "Friends : ";
        self.render = function()
        {
           impact.util.render(self);
        }

    },
    
    facebook_get_my_posts: function()
    {
      var self = this;
      
      self.title = "My Posts: ";
      self.render = function()
      {
         impact.util.render(self);
      }
    },
    
    facebook_get_comments: function()
    {
      var self = this;
      
      self.title = "Comments: ";
      self.render = function()
      {
         impact.util.render(self);
      }
    },
    
    facebook_get_fan_posts: function()
    {
      var self = this;
      
      self.title = "Fan Posts: ";
      self.render = function()
      {
    	  //alert(self.data.toSource());
         impact.util.render(self);
      }
    },
    facebook_get_page_views: function()
    {
      var self = this;
      
      self.title = "Page Views/day: ";
      self.render = function()
      {
    	  //alert(self.data.toSource());
         impact.util.render(self);
      }
    },

    facebook_get_page_likes: function()
    {
      var self = this;
      self.title = "Page Likes: ";
      self.render = function()
      {
         impact.util.render(self);
      }
    },

    facebook_get_album_likes: function()
    {
      var self = this;
      self.title = "Album Likes: ";
      self.render = function()
      {
         impact.util.render(self);
      }
    },

    facebook_get_video_likes: function()
    {
      var self = this;
      self.title = "Video Likes: ";
      self.render = function()
      {
         impact.util.render(self);
      }
    },
    
    twitter_get_tweets: function()
    {
      var self = this;
      self.title = "Tweets by Me: ";
      self.render = function()
      {
    	 
    	impact.util.render(self);
    	  
		//var b = String(self.data.values[0].data.value)
		//var temp = new Array();
		//temp = b.split(',');
		//$(self.element).empty().addClass('small')
		//$(self.element).append('<div class="widget-label">Tweets :</div>');
		//$(self.element).append('<div class="widget-list">');
		//for (i=0; i<temp.length; i++) 
		//  $(self.element).append(''+temp[i]+'<br /><hr>');
		//$(self.element).append('<div class="widget-icons">&nbsp;a</div>');
		//$(self.element).append('<br /></div>');

      }

    },
    
    get_google_search_web: function()
    {
    	var self = this;
    	
    	self.render = function()
        {
    		alert(self.data.toSource());
    		$(self.element).empty().addClass('small');
       	 	$(self.element).append('<div class="widget-label">Search :</div>');
    		
        }
        
    },
    
    get_google_search_blog: function()
    {
    	var self = this;
    	
    	self.render = function()
        {
    		$(self.element).empty().addClass('small')
       	 	$(self.element).append('<div class="widget-label">Blog Search :</div>');
    		
        }
        
    },
    
    get_google_search_news: function()
    {
    	var self = this;
    	
    	self.render = function()
        {
    		$(self.element).empty().addClass('small')
       	 	$(self.element).append('<div class="widget-label">News Search :</div>');
    		
        }
        
    },



    twitter_get_followers: function()
    {
      var self = this;
      self.render = function()
      {
         self.title = "Followers: "+self.connections.Twitter.username;
         console.log(self.connections)
         impact.util.render(self);
      }
    },

    twitter_get_mentions: function()
    {
      var self = this;
      self.render = function()
      {
          var b = String(self.data.values[0].data.value)
    	  var temp = new Array();
    	  temp = b.split(',');

    	 $(self.element).empty().addClass('small')
    	 $(self.element).append('<div class="widget-label">Mentions :</div>');

    	 $(self.element).append('<div class="widget-list">');
    	 for (i=0; i<temp.length; i++) {
    		 $(self.element).append(''+temp[i]+'<br /><hr>');
		  }
    	 $(self.element).append('<br /></div>');
    	 $(self.element).append('<div>&nbsp;</div>');
      }

    },


    twitter_get_retweets: function()
    {
      var self = this;
     
      self.render = function()
      {
         //$(self.element).empty().addClass('small')
         //$(self.element).append("Tweets "+self.data.values[0].data.value)

          var b = String(self.data.values[0].data.value)
    	  var temp = new Array();
    	  temp = b.split(',');

    	 $(self.element).empty().addClass('small')
    	 $(self.element).append('<div class="widget-label">Retweets :</div>');

    	 $(self.element).append('<div class="widget-list">');
    	 for (i=0; i<temp.length; i++) {
    		 $(self.element).append(''+temp[i]+'<br /><hr>');
		  }
    	 $(self.element).append('<br /></div>');
    	 $(self.element).append('<div class="widget-icons">&nbsp;</div>');
      }

    },


    twitter_get_hashtag_search: function()
    {
        var self = this;
        self.render = function()
        {
           self.title = "Hashtag: ["+self.selector_values.hashtag+"]";
           impact.util.render(self);
        }
    },


    google_analytics_get_page_views: function()
    {
      var self = this;

      self.render = function()
      {
        self.title = "Page Views: ["+self.selector_display_values.account+"]";
        impact.util.render(self);
      }

    },

    google_analytics_get_site_visit: function()
    {
      var self = this;
      self.render = function()
      {
         self.title = "Site Visits: ["+self.selector_display_values.account+"]";
         impact.util.render(self);
      }

    },

    google_analytics_get_page_per_visit: function()
    {
      var self = this;
      self.render = function()
      {
         self.title = "Pages Per Visits: ["+self.selector_display_values.account+"]";
         impact.util.render(self);
      }

    },

    google_analytics_get_bounce_rate: function()
    {
      var self = this;
      self.title = "Bounce Rate: ";
      self.render = function()
      {
         impact.util.render(self);
      }

    },

    google_analytics_get_referrers: function()
    {
      var self = this;
      self.render = function()
      {
    	  var b = String(self.data.values[0].data.value)
    	  var temp = new Array();
    	  temp = b.split(',');

    	 $(self.element).empty().addClass('small')
    	 $(self.element).append('<div class="widget-label">Top 5 Referrers (Source) : <span style="color: #404142;">'+self.data.values[0].data.title+'</span></div>');

    	 $(self.element).append('<div class="widget-list">');
    	 for (i=0; i<temp.length; i++) {
    		 $(self.element).append('&nbsp;&nbsp; - &nbsp;'+temp[i]+'<br />');
		  }
    	 $(self.element).append('<br /></div>');
    	 $(self.element).append('<div class="small">on '+self.data.values[0].data.date+'</div>')
    	 $(self.element).append('<div class="widget-icons">&nbsp;</div>');
      }
    },

    google_analytics_get_absolute_unique_visitors: function()
    {
      var self = this;
      self.title = "Absolute Unique Visitors: ";
      self.render = function()
      {
         impact.util.render(self);
      }
    },

    google_analytics_get_percent_new_visits: function()
    {
      var self = this;
      self.title = "New Visits: ";
      self.render = function()
      {
         impact.util.render(self);
      }
    },

    google_analytics_get_browsers: function()
    {
      var self = this;

      self.render = function()
      {
    	 var b = String(self.data.values[0].data.value)
    	 var temp = new Array();
    	 temp = b.split(',');

    	 $(self.element).empty().addClass('small')
    	 $(self.element).append('<div class="widget-label">Top 5 Browsers : <span style="color: #404142;">'+self.data.values[0].data.title+'</span></div>');

    	 $(self.element).append('<div class="widget-list">');
    	 for (i=0; i<temp.length; i++) {
    		 $(self.element).append('&nbsp;&nbsp; - &nbsp;'+temp[i]+'<br />');
		  }
    	 $(self.element).append('<br /></div>');
    	 $(self.element).append('<div class="small">on '+self.data.values[0].data.date+'</div>')
    	 $(self.element).append('<div class="widget-icons">&nbsp;</div>');

      }

    },

    google_analytics_get_connection_speed: function()
    {
      var self = this;
      self.render = function()
      {
    	 var b = String(self.data.values[0].data.value)
    	 var temp = new Array();
    	 temp = b.split(',');

    	 $(self.element).empty().addClass('small')
    	 $(self.element).append('<div class="widget-label">Top 5 Connection Speed : <span style="color: #404142;">'+self.data.values[0].data.title+'</span></div>');

    	 $(self.element).append('<div class="widget-list">');
    	 for (i=0; i<temp.length; i++) {
    		 $(self.element).append('&nbsp;&nbsp; - &nbsp;'+temp[i]+'<br />');
		  }
    	 $(self.element).append('<br /></div>');
    	 $(self.element).append('<div class="small">on '+self.data.values[0].data.date+'</div>')
    	 $(self.element).append('<div class="widget-icons">&nbsp;</div>');
      }

    },

    google_analytics_get_avg_time_on_site: function()
    {
      var self = this;
      self.title = "Avg. time on Site: ";
      self.render = function()
      {
         impact.util.render(self);
      }
    },

    you_tube_get_views: function()
    {
      var self = this;
      self.title = "YouTube views: ";
      self.render = function()
      {
         impact.util.render(self);
      }
    },

    you_tube_get_channel_views: function()
    {
      var self = this;
      self.title = "Channel views: ";
      self.render = function()
      {
         impact.util.render(self);
      }
    },

    you_tube_get_channel_subscribers: function()
    {
      var self = this;
      self.title = "Channel Subscribers: ";
      self.render = function()
      {
         impact.util.render(self);
      }
    },

    vimeo_get_views: function()
    {
      var self = this;
      self.title = "Vimeo views: ";
      self.render = function()
      {
         impact.util.render(self);
      }
    },

    vimeo_get_channel_views: function()
    {
      var self = this;
      self.title = "Vimeo Channel Subscribers: ";
      self.render = function()
      {
         impact.util.render(self);
      }
    },
    
   


    /* custom0 */
    custom_text: function()
    {
      var self = this;

      self.render = function()
      {
          var t = self.props.text;
          if (t == null)
        	  t = "This is where I can enter a description of my project, etc.";
         $(self.element).append(t).css({'font-size':'29px'});
         $(self.element).append('<div class="widget-icons">&nbsp;</div>');
      }
    },

    custom_embed: function()
    {
      var self = this;
      self.render = function()
      {
          var t = self.props.title;
          if (t == null)
        	  t = "Embed";
          $(self.element).append(t);
          $(self.element).append(self.props.embed);
          $(self.element).append(self.props.description);
      }
    },

    custom_manual_or_xml: function()
    {
      var self = this;
      self.render = function()
      {
          impact.util.render(self);
       }
    }

  },

  /* 
   * the following render handles all trend cases
   * the 'total' function tries to adapt to various cases, although some of the rounding functionality was removed
   * the image was removed because it is not part of the design
   * the function assumes that the main # is here: self.data.values[0].data.value
   */
  util:
  {
	render: function(self)
	{
		$(self.element).empty();
	  	self.paper.clear();
        switch(self.props['display-style'])
        {
          case 'total':
        	  impact.util.total(self);
        	  break;
          case 'percent-change':
        	  impact.util.percent_change(self);
        	  break;
          case 'percent-complete':
        	  impact.util.percent_complete(self);
        	  break;
          case 'trend':
        	  impact.util.trend(self);
    		  break;
          case 'map':
 			  impact.util.map(self)
 			  break;
        }
	},
	
	add_commas: function (nStr)
	{
	  nStr = String(nStr);
	  x = nStr.split('.');
	  x1 = x[0];
	  x2 = x.length > 1 ? '.' + x[1] : '';
	  var rgx = /(\d+)(\d{3})/;
	  while (rgx.test(x1))
	    x1 = x1.replace(rgx, '$1' + ',' + '$2');
	  return x1 + x2;
	},
	
	number_to_size: function(n) 
	{
	  var unit = 1000;
	  if (n<unit)
		  return n;
	  var size_suffixes = ['k','M','G','T','P','E','Z','Y'];
	  var i = parseInt(Math.floor(Math.log(n) / Math.log(unit)));
	  if (i<1)
		  return impact.util.add_commas(n);
	  var nn = (n / Math.pow(unit, i)).toFixed(1);
	  if (nn>=100)
		  nn = Math.floor(nn);
	  return nn + '' + size_suffixes[i-1];
	},
	
	total: function(self)
    {
	   $(self.element).addClass('small');
	   var title = "";
	   if (self.title!=null)
		   title = self.title;
	   else if (self.props.title!=null)
		   title = self.props.title;
	   $(self.element).append('<div class="widget-label">'+title+'</div>');

//	   if (self.data.values[0].data.title!=null)
//	   	   $(self.element).append(<span style="color: '+self.color+';">'+self.data.values[0].data.title+'</span>';
	   
//	   if (self.data.values[0].data.thumb!=null)
//		   $(self.element).append("<img src='"+self.data.values[0].data.thumb+"'/><br /><br />");

	   var c = -1;
	   if (self.data.values.length!=0)
		   c = self.data.values[0].data.value;
	   else
		   c = self.props['custom-count'];
	   var cs = String(Math.round(c));
	   var cs = impact.util.add_commas(cs);
	   if (self.width<500)
	   {
		    cs = impact.util.number_to_size(c);
	   }
	   $(self.element).append('<div class="widget-value">'+cs+'</div>');
	   
  	   if (self.data.values.length!=0 && self.data.values[0].data.date != null)
 	      $(self.element).append('<div class="small">on '+self.data.values[0].data.date+'</div>');
  	   
 	   $(self.element).append('<div class="widget-icons">&nbsp;</div>');
    },
    
    percent_change: function(self)
    {
    	var today = self.data.values[0].data.value;
    	var old = self.data.values[self.data.values.length-1].data.value;
    	var percent_change = (today-old)/old;
    	var up_or_down = percent_change<0 ? "down" : "up";
  	    $(self.element).append('<div class="widget-label">'+self.title+'</div>');
 	    $(self.element).append('<div class="widget-value">'+Math.round(today)+'</div>');
	    $(self.element).append('<div class="small">'+up_or_down+' '+Math.round(Math.abs(percent_change*100))+'%</div>');
   	
    },
    
    percent_complete: function(self)
    {
  	    $(self.element).append('<div class="widget-label">'+self.title+'</div>');

  	    var value = self.data.values[0].data.value;
    	var goal = self.props.goal;
    	var percent = value/goal; 
    	
    	var arc = function (center, radius, startAngle, endAngle) {
    	    angle = startAngle;
    	    coords = toCoords(center, radius, angle);
    	    path = "M " + coords[0] + " " + coords[1];
    	    while(angle<=endAngle) {
    	        coords = toCoords(center, radius, angle);
    	        path += " L " + coords[0] + " " + coords[1];
    	        angle += 1;
    	    }
    	    return path;
    	}
    	var toCoords = function (center, radius, angle) {
    	    var radians = (angle/180) * Math.PI;
    	    var x = center[0] + Math.cos(radians) * radius;
    	    var y = center[1] + Math.sin(radians) * radius;
    	    return [x, y];
    	}
    	
    	var m = Math.min(self.width, self.height);
    	var r = m*.5-20;
    	var cx = self.width*.5;
    	var cy = self.height*.75;
    	
    	var gx = toCoords([cx,cy], r+30, -180*(1-Math.min(1,percent)));
 		self.paper.path(arc([cx,cy], r, -180, 0)).attr({ "stroke-width": 33});
 		self.paper.path(["M",cx,cy,"L",gx[0],gx[1]]).attr({ "stroke-width": 1, "stroke": "#0f0"});
 		
         
    	$(self.element).append(Math.round(self.data.values[0].data.value)+" of "+self.props.goal);
    },

    trend: function(self)
    {
 	    var title = "";
	    if (self.title!=null)
		   title = self.title;
	    else if (self.props.title!=null)
		   title = self.props.title;
  	    $(self.element).append('<div class="widget-label">'+title+'</div>');

  	    var e = $(self.element);
		var dvals = self.data.values;
		var events = self.data.events;

		impact.util.line(self,dvals);

    },
	
	map: function(self,geo_values)
	{
		var geo_values = self.data.values[0].data.geo_values;
		
		
		if (geo_values==null)
			throw new Error("Cannot find geo data.");

	 	var current = null;
		var map = {};
		var m = {};

		var attr = {
			fill: "#333",
			stroke: "#888",
			"stroke-width": .5,
			"stroke-linejoin": "round"
		};

		var tx = -110;
		var ty = -70;
		var s = 1.2;

		var map = {};
		var map_set = render_map_set(self.paper,map,attr);
		map_set.translate(tx,ty)
		map_set.scale(s,s,0,0);

		var f = 2.6938 * s;
		var xoffset = (465.4+tx) * s;
		var yoffset = (227.066+ty) * s;
		var lon2x = function (lon) { return (lon * f) + xoffset; }
		var lat2y = function (lat) { return (lat * -f) + yoffset; }
		for (var i=0; i<geo_values.length; i++)
		{
			var g = geo_values[i];
			var c = self.paper.circle(lon2x(g.longitude), lat2y(g.latitude), g.scale==null ? 5 : g.scale).attr({
				fill: "#0f0",
				stroke: "none",
				opacity: .8
			});
			c.val = geo_values[i].scale
			c.click(function(){
				alert(this.val)
			})

		}

//		for (var state in map)
//		{
//			map[state].color = Raphael.getColor();
//            (function (st, state) {
//				st[0].style.cursor = "pointer";
//
//				st[0].onmouseover = function () {
//					current && map[current].animate({fill: "#333", stroke: "#666"}, 300);
//					st.animate({fill: st.color, stroke: "#ccc"}, 300);
//					self.paper.safari();
//					current = state;
//
//				};
//				st[0].onmouseout = function () {
//					st.animate({fill: "#333", stroke: "#666"}, 300);
//					self.paper.safari();
//				};
//
//				st[0].onclick = function () {
//					alert(state);
//				};
//			})(map[state], state);
//		}
	},
	line: function(self, dvals,dvalmin,dvalmax)
	{
		/* get min, max from data */
		if(!dvalmin)
		{
			dvalmin = dvals[0].data.value;		
			dvalmax = dvals[0].data.value;
			for(var i = 1;i < dvals.length;i++)
			{
				dvalmin = Math.min(dvalmin, dvals[i].data.value);
				dvalmax = Math.max(dvalmax, dvals[i].data.value);
			}
		}
		var dvalrange = Math.abs(dvalmax - dvalmin);
		
		var show_legend = self.height> 210;

		/* define margins */
		var yo = 50; //from top
		var xo = show_legend ?  56 : 0; //from left
		var bo = show_legend ? 100 : 28; // from bottom 
		var margin = show_legend ? 0 : 5; // from left * right
		
		var w = (self.width-margin*2-xo) / (dvals.length-1);
		var h = self.height-yo-bo;

		/* x is indexed from left to right */
		var getx = function(idx) 
		{
			return self.width-margin-idx*w ;
		}
		/* y is computed from a value unless the range is 0 (centered by default) */
		var gety = function(val)
		{
			return Math.floor( (dvalrange == 0) ? h*.5 : h-(((val-dvalmin)/dvalrange)*h) ) + yo;
		}
		
		/* horizontal lines */
		var num_horz_lines = 10;
		var unit_space = dvalrange/num_horz_lines;
		var screen_space = h/num_horz_lines;
		for (var i=0; i<(num_horz_lines+1); i++)
		{
			var last = i==num_horz_lines;
			var y = Math.floor(i*screen_space)+yo;
			var path = "M "+xo+" "+y+" L "+self.width+" "+y;
			self.paper.path(path).attr({'stroke': last?'#333':'#e0e0df','stroke-width': .5});
		}
		if (show_legend)
		{
			if (dvalrange == 0)
				num_horz_lines = 0;
			for (var i=0; i<(num_horz_lines+1); i++)
			{
				var v = (i*unit_space)+dvalmin;
				var y = gety(v);
				self.paper.text(40,y,Math.floor(v)).attr({fill: '#444', "font-family": 'Arial', "font-size": "10px", 'text-anchor': 'end'});
			}
		}
		/* define circle macro for graph rollover */
		var circle = function(x,y,val)
		{
			var m = self.paper.circle(x,y,w*.5).attr({'fill':'#0f0','opacity':0})
			var c = self.paper.circle(x,y,5).attr({'fill':'#799fc0', opacity: 0, 'stroke': '#fff'})
			m.val = val;
			m.c = c;
			m.click(function(){alert(this.val)});
			m.mouseover(function (event) {
			    this.c.attr({opacity: 1});
			});
			m.mouseout(function (event) {
				this.c.attr({opacity: 0});
			});
		}
		if (dvals.length==1)
		{
			var x = self.width*.5;
			var y = h*.5 + yo;
			circle(x,y,dvals[0].data.value);
			return;
		}
		/* finally the graph */
		var path = "";
		for(var i = 0;i < dvals.length;i++)
		{
			var val  = dvals[i].data.value;
			var x = getx(i)
			var y = gety(val);
			if (i==0) 
				path += "M ";
			else
				path += "L ";
			path += x+" "+y+" ";
		}
		self.paper.path(path).attr({stroke: '#799fc0','stroke-width': 2});
		/* and the circles */
		for(var i = 0;i < dvals.length;i++)
		{
			var v  = dvals[i].data.value;
			var x = getx(i)
			var y = gety(v);
			circle(x,y,v);
		}
		
		/* more legend... time/date */
		var mos = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
		var ly = null, lm = null, ld = null, lh = null, ln = null;
		var format_date = function(date)
		{
			var n = date.getMinutes();
			var h = date.getHours();
			var d = date.getDate();
			var m = date.getMonth();
			var y = date.getFullYear();
			if (y!=ly)
			{
				ly = y; lm = m; ld = d; lh = h; ln =n;
				return y+" "+mos[m]+" "+d;
			}
			else if (m!=lm)
			{
				ly = y; lm = m; ld = d; lh = h; ln =n;
				return mos[m]+" "+d;
			}
			else if (d!=ld)
			{
				ly = y; lm = m; ld = d; lh = h; ln =n;
				return d;
			}
			else 
			{
				if (n<10)
					n='0'+n;
				if (h<13)
					return h+":"+n+"AM";
				else return (h-12)+":"+n+"PM";
			}
			
		}
		for(var i = dvals.length-1;i >-1;i--)
		{
			var date = new Date(dvals[i].date);
			var x = getx(i);
			var y = self.height - bo + 3;
			var path = "M "+x+" "+y+" L "+x+" "+(y+5);
			self.paper.path(path).attr({stroke: '#333','stroke-width': .5});
			self.paper.text(x,y+9,format_date(date)).attr({fill: '#444', "font-family": 'Arial', "font-size": "10px"});
		}
	},
	pie: function(self, dvals)
	{

          var cx = self.width/2;
          var cy = self.height/2;
          var r = Math.min(cx, cy)/2;
          var labels =['a','b','c'];
          var stroke ="#F7F5F1";

          var sector = function(cx, cy, r, startAngle, endAngle, params)
	      {
	        var rad = Math.PI / 180;
	        var x1 = cx + r * Math.cos(-startAngle * rad);
	        var x2 = cx + r * Math.cos(-endAngle * rad);
	        var y1 = cy + r * Math.sin(-startAngle * rad);
	        var y2 = cy + r * Math.sin(-endAngle * rad);
	        return self.paper.path(["M", cx, cy, "L", x1, y1, "A", r, r, 0, +(endAngle - startAngle > 180), 0, x2, y2, "z"]).attr(params);
	      }

          var angle = 0,
            total = 0,
            start = .5,
            process = function (j) {
                var value = Math.max(.1,dvals[j].value),//TODO normalize vals
                    angleplus = 360 * value / total,
                    popangle = angle + (angleplus / 2),
                    color = "hsb(.15, 1, " + start + ")",
                    ms = 500,
                    delta = 3,
                    p = sector(cx, cy, r, angle, angle + angleplus, {gradient: "90-" + color + "-" + color, stroke: stroke, "stroke-width": 2});
                    //txt = paper.text(cx + (r + delta + 55) * Math.cos(-popangle * rad), cy + (r + delta + 25) * Math.sin(-popangle * rad), labels[j]).attr({fill: bcolor, stroke: "none", opacity: 0, "font-family": 'Fontin-Sans, Arial', "font-size": "20px"});
                p.mouseover(function () {
                    p.animate({scale: [1.1, 1.1, cx, cy]}, ms, "elastic");
                    //txt.animate({opacity: 1}, ms, "elastic");
                }).mouseout(function () {
                    p.animate({scale: [1, 1, cx, cy]}, ms, "elastic");
                    //txt.animate({opacity: 0}, ms);
                });
                angle += angleplus;
                //chart.push(p);
                //chart.push(txt);
                start += .15;
            };
	        for (var i = 0, ii = dvals.length; i < ii; i++)
	            total += parseFloat(Math.max(.1,dvals[i].value));//TODO normalize vals
	        for (var i = 0; i < ii; i++)
	            process(i);

	   }


  }
}









